package com.faiz.algorithm;

import lombok.Data;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

public class AlienSorted {

    private final Map<Character, Integer> dict = new HashMap<>();

    public boolean isAlienSorted(String[] words, String order) {
        init(order);
        MyComparator comparator = new MyComparator();
        for (int i = 0; i < words.length; i++) {
            for (int j = i + 1; j < words.length; j++) {
                int res = comparator.compare(words[i], words[j]);
                if (res > 0) return false;
            }
        }
        return true;
    }

    private void init(String order) {
        char[] chars = order.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            dict.put(chars[i], i);
        }
    }

    private class MyComparator implements Comparator<String> {

        @Override
        public int compare(String o1, String o2) {
            int l = Math.min(o1.length(), o2.length());
            for (int i = 0; i < l; i++) {
                int v1 = dict.get(o1.charAt(i));
                int v2 = dict.get(o2.charAt(i));
                if (v1 > v2) return 1;
                else if (v2 > v1) return -1;
            }
            // 防止出现"app"和"applet"的现象
            return Integer.compare(o1.length(), o2.length());
        }
    }

    public static void main(String[] args) {
        String[] words = {"hello", "leetcode"};
        String order = "hlabcdefgijkmnopqrstuvwxyz";
        AlienSorted alienSorted = new AlienSorted();
        boolean alienSorted1 = alienSorted.isAlienSorted(words, order);
        System.out.println(alienSorted1);
    }
}
